package me.pppploi8.webmcs.main.filter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import me.pppploi8.webmcs.http.jetty.HttpFilter;

/**
 * CSRF过滤器类，用于验证token是否合法，以预防CSRF攻击
 * @author pppploi8
 *
 */
public class WebmcsCSRFFilter implements HttpFilter{

	@Override
	public boolean handle(HttpServletRequest request, HttpServletResponse response) {
		// 读取request中的token和session中的是否相同
		String sessionToken = (String)request.getSession().getAttribute("token");
		String requestToken = request.getParameter("token");
		if (sessionToken != null && sessionToken.equals(requestToken)){
			return true;
		}
		try {
         	response.getOutputStream().write("{\"status\":false,\"msg\":\"TOKENERROR\"}".getBytes());
         	response.getOutputStream().flush();
        } catch (Exception e) { }
		return false;
	}

}
